import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { AvatarDropdown } from './components/RightContent/AvatarDropdown';
import { requestConfig } from './requestConfig';


const loginPath = '/user/login';
const redirect = '/redirect';


/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<InitialState> {
  const initialState: InitialState = {
    currentUser: undefined,
  };
  const { location } = history;
  const token = sessionStorage.getItem('tokenValue');
  if(location.pathname === redirect){
    return initialState;
  }
  // 如果没有toekn而且不是登录页面，重定向到登录页面
  else if (!token && location.pathname !== loginPath) {
      history.push(loginPath);
  } 
  else {
    try {
      // 持久化存储用户信息
      let currentUser = JSON.parse(sessionStorage.getItem('currentUser')||'');
      initialState.currentUser = currentUser;
    } 
    catch (error) {
      // 处理错误，清除令牌并重定向到登录页面
      sessionStorage.removeItem('tokenValue');
      sessionStorage.removeItem('currentUser');
      history.push(loginPath);
    }
  }
  return initialState;
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
// @ts-ignore
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    avatarProps: {
      render: () => {
        return <AvatarDropdown/>;
      },
    },
    //设置水印
    waterMarkProps: {
      content: initialState?.currentUser?.userAccount,
    },
    // footerRender: () => <Footer />,
    menuHeaderRender: undefined,
    ...defaultSettings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = requestConfig;
